package com.heima.article.service.impl;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.message.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    ApArticleConfigService apArticleConfigService;
    @Autowired
    ApArticleContentService apArticleContentService;
    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    GeneratePageService generatePageService;

    /**
     * 保存或修改文章
     * @param newsId 文章id
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 300000)
    @Override
    public void publishArticle(Integer newsId) {
        //1.根据文章id查询自媒体文章信息
        WmNews wmNews = getWmNews(newsId);
        //2.根据wmNews信息封装ApArticle对象
        ApArticle article = getApArticle(wmNews);
        //3.保存或修改apArticle对象
        saveOrUpdateArticle(article);
        //4.保存配置信息 和 内容信息
        saveConfigAnfdContent(wmNews, article);
        //5. 页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),article);
        //6.修改WmNews的状态，将状态修改为9，并设置上关联的articleId
        updateWmNews(newsId, wmNews, article);
        //7.TODO：MQ通知es索引库  更新文章索引
    }

    @Autowired
    ApArticleMapper apArticleMapper;
    @Value("${file.oss.web-site}")
    String webSite;

    @Value("${file.minio.readPath}")
    String readPath;

    /**
     * 查询文章列表
     * @param dto
     * @param type 0：加载更多   1：加载最新
     * @return
     */
    @Override
    public ResponseResult load(Short type, ArticleHomeDTO dto) {

        //1 参数校验
        //时间校验
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        //每页显示条数校验
        if (dto.getSize() == null || dto.getSize() <= 0) {
            dto.setSize(10);
        }
        //频道校验
        if (Strings.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //类型判断
        if (!ArticleConstants.LOADTYPE_LOAD_MORE.equals(type) && !ArticleConstants.LOADTYPE_LOAD_NEW.equals(type)) {
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //2 查询ApArticle数据库
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, type);
        //3 封装查询到的数据（image没有前缀，需要添加上前缀
        for (ApArticle article : articleList) {
            article.setStaticUrl(readPath + article.getStaticUrl());
            //获取文章封面字段
            String images = article.getImages();
            if (Strings.isNotBlank(images)) {
                images = Arrays.stream(images.split(","))
                        .map(url -> webSite + url)
                        .collect(Collectors.joining(","));
                article.setImages(images);
            }
        }
        return ResponseResult.okResult(articleList);
    }

    /**
     *  方法体-修改WmNews的状态
     */
    private void updateWmNews(Integer newsId, WmNews wmNews, ApArticle article) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(article.getId());
        ResponseResult updateResult = wemediaFeign.updateWmNews(wmNews);
        if (!updateResult.checkCode()) {
            log.error("文章发布失败 远程调用修改文章接口失败， 不予发布 , 文章id : {} ", newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用修改文章接口失败");
        }
    }

    /**
     *  方法体-保存配置信息 和 内容信息
     * @param wmNews
     * @param article
     */
    private void saveConfigAnfdContent(WmNews wmNews, ApArticle article) {
        // 添加配置信息
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(article.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigMapper.insert(apArticleConfig);
        // 添加文章详情
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(article.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);
    }

    /**
     *  方法体-保存或修改article对象
     * @param article
     */
    private void saveOrUpdateArticle(ApArticle article) {
        //判断之前wmNews是否关联article
        if (article.getId()==null) {
            // 无关联  新增 article
            article.setCollection(0); // 收藏数
            article.setLikes(0);// 点赞数
            article.setComment(0);// 评论数
            article.setViews(0); // 阅读数
            // 保存文章
            save(article);
        }else {
            // 删除关联的 文章配置信息  和  文章详情信息
            apArticleConfigService.remove(Wrappers.<ApArticleConfig>lambdaQuery()
                    .eq(ApArticleConfig::getArticleId, article.getId()));
            apArticleContentService.remove(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, article.getId()));
            updateById(article);

        }
    }

    /**
     *  方法体-通过wmNews对象构建ApArticle对象
     */
    private ApArticle getApArticle(WmNews wmNews) {
       //1.拷贝属性
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(wmNews,article);
        article.setId(wmNews.getArticleId());
        article.setFlag((byte)0); // 普通文章
        article.setLayout(wmNews.getType());// 布局
        //2.远程查询频道信息
        ResponseResult<AdChannel> result = adminFeign.findOne(wmNews.getChannelId());
        if (!result.checkCode()) {
            log.error("文章发布失败，远程调用admin中频道查询出现异常，不予发布，文章id：{}，频道id：{}",wmNews.getId(),wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用admin微服务查询频道出错了");
        }
        //获取频道信息，判断是否为空
        AdChannel channel = result.getData();
        if (channel==null) {
            log.error("文章发布失败，为查询到相关频道信息，不予发布，文章id：{}，频道id：{}",wmNews.getId(),wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"频道信息不存在");
        }
        article.setChannelName(channel.getName());
        //3.设置作者信息
        ApAuthor author = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (author==null) {
            log.error("文章发布失败，为查询到相关作者的信息，不予发布，文章id：{}，自媒体用户id：{}",wmNews.getId(),wmNews.getUserId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"根据自媒体用户，查询关联作者信息失败");
        }
        article.setAuthorId(Long.valueOf(author.getId()));
        article.setAuthorName(author.getName());

        return article;
    }

    /**
     * 方法体-通过id查询wmNews对象信息
     */
    private WmNews getWmNews(Integer newsId) {
        //1.校验参数
        if (newsId==null) {
            log.error("用户传入的id为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章信息不能为空！！！");
        }
        //远程调用wemedia微服务，查询文章信息
        ResponseResult<WmNews> result = wemediaFeign.findWmNewsById(newsId);
        //判断调用是否正常
        if (!result.checkCode()) {
            log.error("文章发布失败 远程调用自媒体文章接口失败  文章id: {}",newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用wemedia微服务出错了");
        }
        //判断返回数据是否正常
        WmNews wmNews = result.getData();
        if (wmNews==null) {
            log.error("文章发布失败，未获取到自媒体文章信息，文章id：{}",newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到自媒体文章信息");
        }
        // 判断状态是否为 4 或 8， 如果不是  不处理
        short status = wmNews.getStatus().shortValue();
        if (WmNews.Status.SUCCESS.getCode()!=status&&WmNews.Status.ADMIN_SUCCESS.getCode()!=status) {
            log.error("文章状态错误，文章状态不是4 或者 8 ，不予发布，文章id：{}",newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"自媒体状态错误");
        }
        return wmNews;
    }
}